<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button type="primary" :icon="Upload" plain @click="batchAdd">导入数据</el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <BusinessModelAttributeDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="BusinessModelAttribute">
import { ref, reactive, computed, onMounted } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import BusinessModelAttributeDrawer from "./businessModelAttributeDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Download, Upload } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { useDownload } from "@/hooks/useDownload";
import { ElMessageBox } from "element-plus";
import { useDateFormat } from "@vueuse/core";
import { ExportColType } from "@/enums/sysEnum";
import { Model } from "../modeTypes";
import { useDataStore } from "@/stores/modules/data";
import { dateRender, enName2CnNameRender, enumRender, refRender, userRender } from "@/hooks/useColumnRender";

// ProTable 实例
const proTable = ref<ProTableInstance>();
const dataStore = useDataStore();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  condition: {},
  options: { sort: { sort: 1 } }
});

const userList = computed(() => dataStore.userList);
const dataFromList = computed(() => dataStore.getEnumByCsName("dataFrom"));
const dataElements = computed(() => dataStore.dataElements);

onMounted(() => {
  dataStore.findUserList();
  dataStore.findEnumByCsName("dataFrom");
  dataStore.findDataElements();
});

const initVar = reactive({
  tbName: "businessModelAttribute"
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  return apiService.findPage(initVar.tbName, params.condition, params.options);
};

// 表格配置项
const columns = reactive<ColumnProps<Model.BusinessModelAttribute>[]>([
  { type: "index", label: "序号", width: 65 },
  { prop: "businessModelCnName", label: "业务模型", width: 150 },
  { prop: "cnName", label: "中文名称", search: { el: "input", like: true }, width: 150 },
  { prop: "enName", label: "英文名称", search: { el: "input", like: true }, width: 150 },

  {
    prop: "dataElementCnName",
    label: "数据元素",
    width: 150,
    render: scope => enName2CnNameRender(scope, dataElements),
    fieldNames: { value: "enName", label: "cnName" }
  },
  {
    prop: "description",
    label: "描述",
    width: 200,
    render: scope => refRender(scope, dataElements, "dataElementCnName", "enName", "description"),
    fieldNames: { value: "cnName", label: "description" }
  },
  {
    prop: "dataFrom",
    label: "数据来源",
    width: 120,
    enum: dataFromList,
    search: { el: "select", props: { filterable: true } },
    render: scope => enumRender(scope, dataFromList, "value"),
    fieldNames: { label: "name", value: "value" }
  },

  { prop: "businessDomain", label: "业务领域", search: { el: "input", like: true }, width: 120 },

  { prop: "ownerUser", label: "负责人", search: { el: "input", like: true }, width: 100 },
  { prop: "create_user", label: "创建人", width: 100, render: scope => userRender(scope, userList) },
  { prop: "create_at", label: "创建时间", width: 120, render: dateRender },
  { prop: "operation", label: "操作", fixed: "right", width: 220 }
]);

const getExcelConfig = (): any => {
  return {
    params: proTable.value?.searchParam,
    tableName: initVar.tbName,
    keyPropName: "cnName",
    enumTypes: ["dataFrom"],
    tableConfigs: [{ tableName: "users", fields: ["_id", "userName"] }],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "业务模型", width: 20, ext: { prop: "businessModelCnName", type: ExportColType.DEFAULT } },
      { header: "中文名称", width: 15, ext: { prop: "cnName", type: ExportColType.DEFAULT } },
      { header: "英文名称", width: 15, ext: { prop: "enName", type: ExportColType.DEFAULT } },
      { header: "数据元素", width: 20, ext: { prop: "dataElementCnName", type: ExportColType.DEFAULT } },
      {
        header: "数据来源",
        width: 12,
        ext: { prop: "dataFrom", type: ExportColType.ENUM, key: "dataFrom", label: "name", value: "value" }
      },
      { header: "业务领域", width: 15, ext: { prop: "businessDomain", type: ExportColType.DEFAULT } },
      { header: "负责人", width: 12, ext: { prop: "ownerUser", type: ExportColType.DEFAULT } },
      {
        header: "创建人",
        width: 10,
        ext: { prop: "create_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "创建时间", width: 15, ext: { prop: "create_at", type: ExportColType.DATE } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(
      apiService.commonExport,
      `业务模型属性清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`,
      "",
      getExcelConfig(),
      false
    )
  );
};

// 导入数据
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "业务模型属性",
    defaultTip: "中文名称相同则跳过",
    coverTip: "中文名称相同则覆盖",
    isCover: true,
    tempUrl: "/template/businessModelAttribute",
    getTableList: proTable.value?.getTableList,
    importApi: apiService.commonImport,
    config: getExcelConfig()
  };
  dialogRef.value?.acceptParams(params);
};

// 删除业务模型属性
const deleteAccount = async (row: Model.BusinessModelAttribute) => {
  useHandleData(apiService.deleteById, initVar.tbName, row._id, "删除").then(() => proTable.value?.getTableList());
};

// 打开抽屉
const drawerRef = ref<InstanceType<typeof BusinessModelAttributeDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Model.BusinessModelAttribute> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? apiService.save : apiService.updateById,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>

<style scoped lang="scss">
.business-model-attribute-container {
  padding: 20px;
}
</style>
